package com.springboot.centersystem.controller;

import com.springboot.centersystem.entity.Food;
import com.springboot.centersystem.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import com.springboot.centersystem.utils.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Controller
@RequestMapping(value = "/restaurantApi/admin")
public class AdminController {

    static String fileLocation = "/restaurantRes/";//图片资源访问路径
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入业务对象
    @Resource
    private AdminService adminService;
    @PostMapping("/addFood")
    @ResponseBody
    public Map<String, Object> uploadFood(String description, Part pictureFile,
                                          HttpServletRequest request) {
        //获取提交文件名称
        String filename = pictureFile.getSubmittedFileName();
        //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + filename;

        String pictureFileURL = filePath;//根路径+文件名

//插入这条Food数据
        adminService.insertFood(new Food( description, pictureFileURL));

        //写入文件
        try {
            pictureFile.write(filename);
            result.put("Result", "添加菜品信息成功");
        } catch (IOException e) {
            e.printStackTrace();
            result.put("Result", "添加菜品信息失败");
        }
        return result;
    }


    @GetMapping("/list")
    @ResponseBody
    public List<Food> list(){
        return  adminService.list();
    }


    //  ============文件删除===============
  @GetMapping("deleteid")
    @ResponseBody
    public Boolean  deleteFile(int id) throws IOException {
     //   adminService.delete(id); //删除数据库
    try {
    String deletePath= adminService.selectid(id).getPictureFileURL();
       String cc= deletePath.substring(deletePath.lastIndexOf("/")+1);
       String truepath="d:/restaurantRes/"+cc;
    System.out.println(deletePath);
System.out.println(cc);
File file=new File(truepath);
file.delete();
adminService.delete(id);
    return true;
    }


catch(Exception e){
    e.printStackTrace();
}
    return false;
    }
}